package com.jason.bbs.router.filter;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.jason.bbs.bean.ResultJson;
import com.jason.bbs.router.feign.PmsService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

@Component
//@Configuration
public class PowerFilter extends ZuulFilter {
	@Resource
	private PmsService pmsService;
//	@Value("${excludes}")
	private List<String> excludePath=new ArrayList<>();
	public PowerFilter() {
		this.excludePath.add("/api/pms/**");
	}
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.addZuulRequestHeader("token", "1");
		if (!checkLogin()) {
			ctx.setSendZuulResponse(false);
			ResultJson code = new ResultJson(403, "您无权访问该服务");
			ctx.setResponseBody(JSONObject.toJSONString(code));
		} else {
			ctx.setSendZuulResponse(true);
		}
		return null;
	}

	public boolean checkLogin() {
		RequestContext ctx = RequestContext.getCurrentContext();
		if (excludePath != null) {
			String uri = ctx.getRequest().getRequestURI();
			AntPathMatcher apm = new AntPathMatcher();
			for (String path : excludePath) {
				if (apm.match(path, uri)) {
					return true;
				}
			}
		}

		String loginId = ctx.getRequest().getHeader("loginId");
		ResultJson rs = this.pmsService.checkLogin(loginId);
		if (rs.getCode() != 200 || (Boolean) rs.get("existis") == false) {
			return false;
		}
		return true;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
